package com.yinpeng.consul_consumer;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class DcController {

    private final LoadBalancerClient loadBalancerClient;
    private final RestTemplate restTemplate;

    public DcController(LoadBalancerClient loadBalancerClient, RestTemplate restTemplate) {
        this.loadBalancerClient = loadBalancerClient;
        this.restTemplate = restTemplate;
    }

    @GetMapping("/consumer")
    public String dc() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("consul-client"); // 选取客户端实例
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc"; // 拼接url
        System.out.println("--- 手动选取客户端实例和拼接url发起调用：" + url + " ------");
        return new RestTemplate().getForObject(url, String.class);
    }

    @GetMapping("/consumer-ribbon")
    public String dcRibbon() {
        System.out.println("--- 通过ribbon负载均衡客户端发起调用 ---");
        return restTemplate.getForObject("http://consul-client/dc", String.class);
    }
}
